package com.lilihub.miaosha.controller;

import com.lilihub.miaosha.common.Result;
import com.lilihub.miaosha.domain.MiaoshaUser;
import com.lilihub.miaosha.redis.GoodKey;
import com.lilihub.miaosha.service.GoodsService;
import com.lilihub.miaosha.service.MiaoshaUserService;
import com.lilihub.miaosha.service.RedisService;
import com.lilihub.miaosha.vo.GoodsDetailVo;
import com.lilihub.miaosha.vo.GoodsVo;
import com.sun.corba.se.spi.ior.IdentifiableFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.jta.JtaAfterCompletionSynchronization;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.context.webflux.SpringWebFluxContext;
import org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;


/**
 * @BelongsProject: miaosha2
 * @BelongsPackage: com.lilihub.miaosha.controller
 * @Author: LiYing
 * @CreateTime: 2021-04-26 15:43
 * @Description:
 */

@Controller
@RequestMapping("/goods")
public class GoodsController {


    @Autowired
    private MiaoshaUserService userService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;


    @RequestMapping(value = "to_list",produces = "text/html")  //直接返回html的源代码
    @ResponseBody
    public String toLogin(Model model, MiaoshaUser user,
                          HttpServletRequest request,
                          HttpServletResponse response){

        model.addAttribute("user", user);

        //取缓存
        String html = redisService.get(GoodKey.getGoodList, "", String.class);
        if (!StringUtils.isEmpty(html)){
            return html;
        }


        //查询商品列表
        List<GoodsVo> goodsList = goodsService.getGoodsVoList();
        model.addAttribute("goodsList", goodsList);
//        return "goods_list";

        //手动渲染模板
        WebContext ctx = new WebContext(request,response,
                            request.getServletContext(),request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if (!StringUtils.isEmpty(html)){
            redisService.set(GoodKey.getGoodList, "", html);
        }

        //结果输出
        return html;
    }


    @RequestMapping(value = "to_detail2/{goodsId}",produces = "text/html")  //直接返回html的源代码
    @ResponseBody
    public String detail2(Model model, MiaoshaUser user,
                         @PathVariable("goodsId") Long goodsId,
                         HttpServletRequest request,
                         HttpServletResponse response){

        model.addAttribute("user", user);

        //取缓存
        String html = redisService.get(GoodKey.getGoodDetail, "" + goodsId, String.class);
        if (!StringUtils.isEmpty(html)){
            return html;
        }

        //手动渲染模板
        GoodsVo goods = goodsService.getGoodsByGoodsId(goodsId);
        model.addAttribute("goods", goods);

        //秒杀是否开始
        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int miaoshaStatus = 0;
        int remainSeconds = 0;

        if (now < startAt){   //秒杀没开始，倒计时
            miaoshaStatus = 0;
            remainSeconds = (int) ((startAt - now)/1000);

        }else if (now > endAt){  //秒杀结束

            miaoshaStatus = 2;
            remainSeconds = -1;

        }else{   //秒杀正在进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }

        model.addAttribute("miaoshaStatus", miaoshaStatus);
        model.addAttribute("remainSeconds", remainSeconds);


        WebContext ctx = new WebContext(request,response,
                request.getServletContext(),request.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        if (!StringUtils.isEmpty(html)){
            redisService.set(GoodKey.getGoodDetail, "" + goodsId, html);
        }

        //结果输出
        return html;


//        return "goods_detail";
    }


    @RequestMapping(value = "detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> detail(MiaoshaUser user,
                                        @PathVariable("goodsId") Long goodsId){

        GoodsVo goods = goodsService.getGoodsByGoodsId(goodsId);

        //秒杀是否开始
        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int miaoshaStatus = 0;
        int remainSeconds = 0;

        if (now < startAt){   //秒杀没开始，倒计时
            miaoshaStatus = 0;
            remainSeconds = (int) ((startAt - now)/1000);

        }else if (now > endAt){  //秒杀结束

            miaoshaStatus = 2;
            remainSeconds = -1;

        }else{   //秒杀正在进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }

        GoodsDetailVo vo = new GoodsDetailVo();
        vo.setGoods(goods);
        vo.setUser(user);
        vo.setMiaoshaStatus(miaoshaStatus);
        vo.setRemainSeconds(remainSeconds);

        return Result.success(vo);

    }









}
